
import threading
from common.utils import *

pa = 'D:/data/220401小鸟/'
pa = 'D:/data/220401小鸟/220609/PO69051不良'
pa = 'D:/data/220329竹筷/220602heibai'
pa = 'D:/data/220901海尔前控板检测/221011/EB65M019'
pa = 'D:/data/220901海尔前控板检测/221011/EB100Z33Nova2/MV-CS200-10GC (K32643633)'
# pa = pa if os.path.exists(pa) else 'D:/data/220901海尔前控板检测/20221016'
pp = [
  'D:/data/221123海尔面板/221123NG/MV-CS200-10GC (K32643633)',  
  'D:/data/221123海尔面板/221123NG/MV-CS200-10GC (K79319324)',  
]

class Value:
    ON = 1
    OFF = 0
    def set(self, x):
        return x
    def is_implemented(self):
        return True

def cam_thread(ss):
    ttt = 2.2
    while(ss.is_stream_on):
        t0 = time.time()
        ss.img = ss.getFrame()
        ss.capture_callback(ss.img)
        tt = time.time()-t0
        if tt<ttt:
            time.sleep(ttt-tt)

def GetCamNum():
    return len(pp)

class MVSCam:

    def __init__(self, index=-1) -> None:
        self.ExposureTime = Value()
        self.TriggerMode = Value()
        self.TriggerSource = Value()
        self.PixelColorFilter = Value()
        self.capture_callback = None
        self.data_stream = []
        if index>=0:
            self.open(index)
        self.i = 0
        self.img = None
        self.is_stream_on = True

    def OpenDevice(self):
        self.open(0)
    
    def CloseDevice(self):
        self.open(0)
    
    def get_numpy_array(self):
        return self.img
    
    def get_status(self):
        return 0
    
    def convert(self, ss):
        return self
    
    def StartContinusAcqCallback(self):
        pass
    
    def stream_on(self):
        self.is_stream_on = True
        self.cam_thread_handle = threading.Thread(target=cam_thread, args=(self,))
        self.cam_thread_handle.start()
    
    def stream_off(self):
        self.is_stream_on = False
        self.cam_thread_handle.join()
    
    def close_device(self):
        pass
    
    def register_capture_callback(self, fun):
        self.capture_callback = fun

    def open(self, index, type='soft', call_back=None):
        self.index = index
        self.type=type
        self.capture_callback = call_back
        pa = pp[index]
        self.li = listdir(pa, ['.jpg', '.png', '.bmp'])
        self.li = [f'{pa}/{x}' for x in self.li]
        self.i = 400
        if type in ['hard']:
            self.stream_on()
        if len(self.li) > 0:
            return 1
        return 0

    def close(self):
        self.i = 0
        return 0

    def stop(self):
        self.i = 0
        return 0

    def getFrame(self):
        if self.i >= len(self.li):
            self.i = 0

        if self.i < len(self.li):
            #print(f'getFrame {self.i} {self.li[self.i]}')
            im = cv_imread(self.li[self.i], 1)
            self.i += 1
            return im

        return None


class DeviceManager:
    def update_device_list(self):
        return 4, []

    def open_device_by_index(self, index):
        return MVSCam(index-1)

GxSwitchEntry = Value()

def test_MVSCams():
    ncam = GetCamNum()
    cams = [MVSCam() for i in range(ncam)]
    [cams[i].open(i) for i in range(ncam)]
    for ii in range(100):
        ims = [cams[i].getFrame() for i in range(ncam)]
        ims = [cv2.resize(ims[i], (640, 480)) for i in range(ncam)]
        [cv2.imshow(f'im{i}', ims[i]) for i in range(ncam)]
        print(ii)
        cv2.waitKey(100)

    [cams[i].stop() for i in range(ncam)]
    print('end')

def test_MVSCam_tri():
    cam = MVSCam()
    import queue
    q = queue.Queue(maxsize=1)
    def frame_callback(im):
        im = cv2.resize(im, (640, 480))
        q.put(im) 

    cam.open(0, 'hard', frame_callback)
    im = np.zeros((480, 640, 3), dtype='uint8')
    for i in range(1000):
        try:
            im = q.get(False, 1)
        except queue.Empty:
            pass
        cv2.imshow('im', im)
        cv2.waitKey(100)
        #print('time out')

    cam.stop()

if __name__ == "__main__":
    test_MVSCams()
    #test_MVSCam_tri()

